let livingRoomCurtainAssembly; // 客厅窗帘

let restaurantCurtainAssembly; // 餐厅窗帘

let bedroomCurtainAssembly; // 卧室窗帘

let balconyCurtainAssembly; // 阳台窗帘

// 收集窗帘所有数组
let curtainAssemblyArray = new Array();

// 窗帘的默认参数
const defaultCurtainParams = {
    windowWidth: 2.0,    // 窗户宽度
    windowHeight: 1.2,   // 窗户高度
    windowY: 0.8,       // 窗户Y坐标
    segmentCount: 12,    // 窗帘片数量
    rodRadius: 0.02,     // 窗帘杆半径
    ringRadius: 0.03,    // 窗帘环半径
    ringThickness: 0.01,  // 窗帘环厚度
    frontColor: 0xf5deb3, //前窗帘的颜色
    backColor: 0xf8ecc9, //后窗帘的颜色
    rodColor: 0x888888, //窗帘杆的颜色
    ringColor: 0xcccccc, // 窗帘环的颜色
    x: 0, // 窗帘的X坐标
    y: 0, // 窗帘的Y坐标
    z: 0, // 窗帘的Z坐标

}


// 创建复用性函数
function createCurtainMore(params = {}, curtainAssembly) {
    // 添加参数
    curtainAssemblyArray.push({
        key: `${curtainAssembly}`,
        value: curtainAssembly,
        params: params,
    })
    // 合并参数
    const mergedParams = { ...defaultCurtainParams, ...params };
    // 清空旧的窗帘
    while (curtainAssembly.children.length > 0) {
        curtainAssembly.remove(curtainAssembly.children[0]);

    }


    const {
        windowWidth,
        windowHeight,
        windowY,
        segmentCount,
        rodRadius,
        ringRadius,
        ringThickness,
        frontColor,
        backColor,
        rodColor,
        ringColor,
        x,
        y,
        z,
    } = mergedParams;


    // 计算窗帘尺寸
    const totalCurtainWidth = windowWidth * 1.1;
    const curtainHeight = windowHeight * 1.2;
    const segmentWidth = totalCurtainWidth / segmentCount;


    // 窗帘杆 - 确保杆子长度与总宽度匹配
    const rodGeometry = new THREE.CylinderGeometry(rodRadius, rodRadius, totalCurtainWidth, 16);
    const rodMaterial = new THREE.MeshStandardMaterial({ color: rodColor });
    const rod = new THREE.Mesh(rodGeometry, rodMaterial);
    rod.rotation.z = Math.PI / 2;
    rod.position.y = windowY + windowHeight / 2 + 0.1;
    rod.position.x = 0; // 杆子居中
    curtainAssembly.add(rod);

    // 窗帘环和窗帘片
    const ringGeometry = new THREE.TorusGeometry(ringRadius, ringThickness, 16, 16);
    const ringMaterial = new THREE.MeshStandardMaterial({ color: ringColor });

    // 窗帘材质
    const frontMaterial = new THREE.MeshStandardMaterial({
        color: frontColor,
        roughness: 0.9,
        metalness: 0.1,
        side: THREE.FrontSide,
    });

    const backMaterial = new THREE.MeshStandardMaterial({
        color: backColor,
        roughness: 0.9,
        metalness: 0.1,
        side: THREE.BackSide,
    });


    // 创建窗帘片和环
    for (let i = 0; i < segmentCount; i++) {
        // 创建带有褶皱的窗帘片几何体
        const segmentGeometry = createPleatedCurtainGeometry(segmentWidth, curtainHeight, 10, 20);

        const frontCurtain = new THREE.Mesh(segmentGeometry, frontMaterial);
        const backCurtain = new THREE.Mesh(segmentGeometry, backMaterial);

        // 初始位置 - 均匀分布在窗帘杆上
        const xPosition = -totalCurtainWidth / 2 + i * segmentWidth + segmentWidth / 2;
        const yPosition = rod.position.y - curtainHeight / 2;

        frontCurtain.position.set(xPosition, yPosition, 0);
        backCurtain.position.set(xPosition, yPosition, 0);

        frontCurtain.castShadow = true;
        backCurtain.castShadow = true;

        // 保存初始位置信息和索引
        frontCurtain.userData = {
            initialX: xPosition,
            index: i,
            segmentWidth: segmentWidth
        };
        backCurtain.userData = {
            initialX: xPosition,
            index: i,
            segmentWidth: segmentWidth
        };

        curtainAssembly.add(frontCurtain);
        curtainAssembly.add(backCurtain);

        // 窗帘环
        const ring = new THREE.Mesh(ringGeometry, ringMaterial);
        ring.position.set(xPosition, rod.position.y, 0);
        ring.userData = {
            initialX: xPosition,
            index: i
        };
        curtainAssembly.add(ring);
    }

    // 设置整个窗帘组的位置
    curtainAssembly.position.set(x, y, z);

}


// 创建带有褶皱感的窗帘几何体
function createPleatedCurtainGeometry(width, height, widthSegments, heightSegments) {
    const geometry = new THREE.PlaneGeometry(width, height, widthSegments, heightSegments);
    const positionAttribute = geometry.getAttribute('position');
    const positions = positionAttribute.array;

    // 添加褶皱效果
    for (let i = 0; i < positions.length; i += 3) {
        const x = positions[i];
        const y = positions[i + 1];

        // 基于位置添加褶皱波动
        const pleatIntensity = 0.03;
        const zOffset = Math.sin(x * Math.PI * 4) * Math.cos(y * Math.PI * 2) * pleatIntensity;

        positions[i + 2] = zOffset;
    }

    positionAttribute.needsUpdate = true;
    geometry.computeVertexNormals();

    return geometry;
}


// 更新窗帘状态 - 修复版：确保窗帘片真正移动
function updateCurtain(params, position, curtainAssembly = null) {

    // 获取当前的窗帘个个参数
    const curtainParams = params;

    if (!curtainAssembly) {
        return;
    }

    const openAmount = position / 100; // 0 到 1 之间




    // 直接遍历 curtainAssembly 的子对象，不再依赖 geometry.type 过滤
    const curtainMeshes = [];
    curtainAssembly.traverse(child => {
        if (child.isMesh && child.userData && child.userData.initialX !== undefined) {
            curtainMeshes.push(child);
        }
    });



    const segmentCount = curtainParams.segmentCount;
    const totalCurtainWidth = curtainParams.windowWidth * 1.1;
    const segmentWidth = totalCurtainWidth / segmentCount;

    // 计算左右边界
    const leftBound = -totalCurtainWidth / 2 + segmentWidth / 2;
    const rightBound = totalCurtainWidth / 2 - segmentWidth / 2;

    curtainMeshes.forEach(mesh => {
        const index = mesh.userData.index;
        const initialX = mesh.userData.initialX;

        // 最左/最右两片作为“固定端”不移动
        if (index === 0 || index === segmentCount - 1) {
            mesh.position.x = initialX;
            return;
        }

        const isLeftSide = index < segmentCount / 2;

        // 目标：左侧片最终叠到最左，右侧片最终叠到最右
        let targetX;
        if (isLeftSide) {
            targetX = leftBound + (index * segmentWidth * 0.1); // 0.35 让叠放更紧凑
        } else {
            targetX = rightBound - ((segmentCount - 1 - index) * segmentWidth * 0.1);
        }

        // 线性插值
        const newX = initialX + openAmount * (targetX - initialX);
        mesh.position.x = newX;

        // 透明度随打开程度变化
        if (mesh.material.transparent !== undefined) {
            // mesh.material.opacity = Math.max(0.2, 0.9 - openAmount * 0.7);
        }

        // 褶皱效果
        if (mesh.geometry.type === 'PlaneGeometry') {
            adjustPleatingEffect(mesh.geometry, openAmount);
            const pileFactor = isLeftSide
                ? (mesh.position.x - leftBound) / (initialX - leftBound)
                : (rightBound - mesh.position.x) / (rightBound - initialX);
            adjustPileEffect(mesh.geometry, pileFactor);
        }
    });
}


// 新增：根据堆积程度调整褶皱效果
function adjustPileEffect(geometry, pileFactor) {
    const positionAttribute = geometry.getAttribute('position');
    const positions = positionAttribute.array;

    if (!geometry.userData.originalPositions) {
        geometry.userData.originalPositions = new Float32Array(positions);
    }

    const originalPositions = geometry.userData.originalPositions;

    // 堆积时增加褶皱效果
    for (let i = 0; i < positions.length; i += 3) {
        const x = originalPositions[i];
        const y = originalPositions[i + 1];

        // 基础褶皱
        const basePleat = Math.sin(x * Math.PI * 4) * Math.cos(y * Math.PI * 2) * 0.03;
        // 堆积褶皱（堆积越多褶皱越明显）
        const pilePleat = Math.sin(x * Math.PI * 8) * pileFactor * 0.05;

        positions[i + 2] = basePleat + pilePleat;
    }

    positionAttribute.needsUpdate = true;
    geometry.computeVertexNormals();
}


// 根据打开程度调整褶皱效果
function adjustPleatingEffect(geometry, openAmount) {
    const positionAttribute = geometry.getAttribute('position');
    const positions = positionAttribute.array;

    // 如果没有保存原始位置，先保存
    if (!geometry.userData.originalPositions) {
        geometry.userData.originalPositions = new Float32Array(positions);
    }

    const originalPositions = geometry.userData.originalPositions;

    // 根据打开程度调整褶皱
    for (let i = 0; i < positions.length; i += 3) {
        const x = originalPositions[i];
        const y = originalPositions[i + 1];

        // 打开时褶皱减少
        const pleatIntensity = 0.03 * (1 - openAmount * 0.8);
        const zOffset = Math.sin(x * Math.PI * 4) * Math.cos(y * Math.PI * 2) * pleatIntensity;

        positions[i + 2] = zOffset;
    }

    positionAttribute.needsUpdate = true;
    geometry.computeVertexNormals();
}

// 调整整个窗帘组的位置（可根据需要调用）
function setCurtainPosition(curtainAssembly = null, x = 0, y = 0, z = 0) {
    if (!curtainAssembly) {
        console.warn("curtainAssembly 尚未初始化");
        return;
    }
    curtainAssembly.position.set(x, y, z);
}

// 调整窗帘尺寸（可根据需要调用）
function resizeCurtain(newWidth, newHeight) {
    curtainParams.windowWidth = newWidth;
    curtainParams.windowHeight = newHeight;
    curtainAssemblyArray.forEach(item => {
        // 根据数组重新制作窗帘
        createCurtainMore(item.params, item.value);
    });
}



